<?php
require_once 'Zend/Db/Tree/Adapter/AdapterInterface.php';

abstract class Zend_Db_Tree_Adapter_AdapterAbstract implements Zend_Db_Tree_Adapter_AdapterInterface
{
    const FETCH_ARRAY  = 'array';
    const FETCH_SELECT = 'select';

    protected $_db;

    protected $_tableName;

    protected $_skipOptions = array();

    protected $_fetchMode;

    public function __construct(array $options = array())
    {
        $this->_fetchMode = self::FETCH_ARRAY;
        if (count($options)) {
            $this->setOptions($options);
        }
    }

    public function setOptions(array $options)
    {
        $this->_options = $options;
        $methods = get_class_methods($this);
        foreach ($methods as $key => $method) {
            $methods[$key] = strtolower($method);
        }
        foreach ($options as $name => $value) {
            $name = strtolower($name);
            if (in_array($name, $this->_skipOptions)) {
                continue;
            }
            $method = 'set' . $name;
            if (in_array($method, $methods)) {
                $this->$method($value);
            }
        }
        return $this;
    }

    public function getOptions()
    {
        return $this->_options;
    }

    public function setDb(Zend_Db_Adapter_Abstract $db)
    {
        $this->_db = $db;
        return $this;
    }

    public function getDb()
    {
        return $this->_db;
    }

    public function setTableName($tableName)
    {
        $this->_tableName = $tableName;
        return $this;
    }

    public function getTableName()
    {
        return $this->_tableName;
    }

    public function setFetchMode($fetchMode)
    {
        $this->_fetchMode = $fetchMode;
        return $this;
    }

    public function getFetchMode()
    {
        return $this->_fetchMode;
    }

    protected function _getTableName()
    {
        if (empty($this->_tableName)) {
            require_once 'Zend/Db/Tree/Adapter/Exception.php';
            throw new Zend_Db_Tree_Adapter_Exception('Table name has not been specified');
        }
        return $this->_tableName;
    }

    /**
     * @return array
     */
    protected function _fetchRow($select)
    {
        if ($this->_fetchMode == self::FETCH_SELECT) {
            return $select;
        }
        $result = $select->query()->fetch(Zend_Db::FETCH_ASSOC);
        return empty($result) ? array() : $result;
    }

    /**
     * @return array
     */
    protected function _fetchAll($select)
    {
        if ($this->_fetchMode == self::FETCH_SELECT) {
            return $select;
        }
        return $select->query()->fetchAll(Zend_Db::FETCH_ASSOC);
    }

    protected function _select()
    {
        return $this->_db->select();
    }
}
